###############################################################################
#drafted by Jeremy VanDerWal ( jjvanderwal@gmail.com ... www.jjvanderwal.com )
#GNU General Public License .. feel free to use / distribute ... no warranties
################################################################################
### define species inputs
timeline='Post_decline'
occur.file = paste('/home/jc148322/frog_declines/',timeline,'.csv',sep='')#the file with your species code, lat and longs
bkgd.file = '/home/jc148322/frog_declines/bkgd.csv'#the file with all occurrence records, lats and longs
wd=paste('/home/jc148322/frog_declines/SDM/',timeline,'/',sep='')# your work directory eg."/home/jc148322/SDM/Random_bkgd/"; 
dir.create(wd); setwd(wd) #define and set the working directory
################################################################################
source('/home/jc148322/scripts/libraries/cool_functions.r')
library(SDMTools)
climate.dir='/home/jc165798/Climate/CIAS/AWT/250m/baseline.76to05/bioclim/'
maxent.jar = "/home/jc165798/working/NARP_birds/maxent.jar" #define the location of the maxent.jar file
#define the species of interest

###prepare the data
bkgd=read.csv(bkgd.file,as.is=TRUE); bkgd$Species='bkgd'
bkgd = bkgd[,1:3]
colnames(bkgd)=c('spp','lat','long')

occur = read.csv(occur.file,as.is=TRUE) #read in the occur file
occur = occur[,1:3]
colnames(occur)=c('spp','lat','long')
occur = unique(na.omit(occur)) #remove any missing data and keep on unique data
clim.vars = paste('bioclim_',sprintf('%02i',c(1,4,5,6,12,15,16,17)),sep='') #define the climate variables of interest
for (clim.var in clim.vars) { cat(clim.var,'\n') #cycle through each of hte climate variables
	tasc=read.asc.gz(paste(climate.dir,clim.var,'.asc.gz',sep=''))
	occur[,clim.var] = extract.data(cbind(occur$long,occur$lat), tasc) #append the climate data
	bkgd[,clim.var] = extract.data(cbind(bkgd$long,bkgd$lat), tasc) #append the climate data	
}
occur = unique(na.omit(occur)) #remove any missing data and keep on unique data
bkgd=unique(na.omit(bkgd))
write.csv(bkgd,'bkgd.csv',row.names=FALSE) #write out your target group background

species=unique(occur$spp)
if (timeline=='Post_decline') species=species[-grep('acuti',species)]

###cycle through each species and submit jobs to be modelled
for (spp in species) { cat(spp,'\n')
	toccur = occur[occur$spp==spp,] #get the observations for the species
	spp.dir = paste(wd,'models/',spp,'/',sep='') #define the species directory
	dir.create(paste(spp.dir,'output',sep=''),recursive=TRUE) #create the species directory
	write.csv(toccur,paste(spp.dir,'occur.csv',sep=''),row.names=FALSE) #write out the file
	 
	#create the shell script which will run the modelling jobs
	zz = file(paste(spp.dir,'01.',spp,'.model.sh',sep=''),'w') #create the shell script to run the maxent model
		cat('#!/bin/bash\n',file=zz)
		cat('cd ',spp.dir,'\n',sep='',file=zz)
		cat('source /etc/profile.d/modules.sh\n',file=zz) 
		cat('module load java\n',file=zz)
		cat('java -mx2048m -jar ',maxent.jar,' -e ',wd,'bkgd.csv -s occur.csv -o output nothreshold nowarnings novisible replicates=10 nooutputgrids -r -a \n',sep="",file=zz) #run maxent bootstrapped to get robust model statistics
		cat('cp -af output/maxentResults.csv output/maxentResults.crossvalide.csv\n',file=zz) #copy the maxent results file so that it is not overwritten
		cat('java -mx2048m -jar ',maxent.jar,' -e ',wd,'bkgd.csv -s occur.csv -o output nothreshold nohinge outputgrids plots nowarnings  responsecurves jackknife novisible nowriteclampgrid nowritemess writeplotdata -P -J -r -a \n',sep="",file=zz) #run a full model to get the best parameterized model for projecting
	close(zz)
	setwd(spp.dir); system(paste('qsub -m n 01.',spp,'.model.sh',sep='')); setwd(wd) #submit the script
}
